/*
    Project:        Home Power Control
    File:           HPCLight.cpp
    Author:         christian@karunamusic.at
    Date:           12.2014
    Description:    Sensor to measure the ambient light with the TSL45315.
 */

#include <wiringPiI2C.h>
#include <unistd.h>
#include <string>
#include "globals.h"
#include "HPCLight.h"

#define REG_CONTROL  0x00
#define REG_CONFIG   0x01
#define REG_DATALOW  0x04
#define REG_DATAHIGH 0x05
#define REG_ID       0x0A

using namespace std;

HPCLight::HPCLight( unsigned long id, unsigned int i2caddr, unsigned int interval )
    : HPCThreadedSensor( id,i2caddr,interval )
{
    PROFILE_THIS;

    m_Old= (unsigned int)0;
    m_I2C = wiringPiI2CSetup( m_Pin );
    // power on...
    wiringPiI2CWriteReg8(m_I2C,0x80|REG_CONTROL,0x03);
    // config...
    wiringPiI2CWriteReg8(m_I2C,0x80|REG_CONFIG,0x02);
}

HPCLight::~HPCLight()
{
    PROFILE_THIS;
    close(m_I2C);
}

void HPCLight::Measure()
{
    PROFILE_THIS;

    wiringPiI2CWrite(m_I2C,0x80|REG_DATALOW);
    m_Value = (unsigned int)wiringPiI2CRead(m_I2C) * 4;
}

bool HPCLight::hasChanged()
{
    PROFILE_THIS;

    Measure();
    LOG( debug, "Measured value: " << (string)m_Value << " " << MeasureUnit() );

    return (m_Value != m_Old);
}
